package com.atguigu.zy.interview.jvm.reference;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

/**
 * @author Jungle
 * @create 2022-09-04 17:31
 *
 * java.lang.Object@76ed5528
 * java.lang.Object@76ed5528  --referenceQueue
 * null
 * ************GC之后************
 * null
 * null
 * java.lang.ref.WeakReference@2c7b84de---referenceQueue
 *  对象被回收之前需要被引用队列保存一下，也就是引用被回收了，队列中才会不为null
 */
public class ReferenceQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        Object o1 = new Object();
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        //WeakReference(T referent, ReferenceQueue<? super T> q)
        WeakReference<Object> weakReference = new WeakReference<>(o1, referenceQueue);
        System.out.println(o1);
        System.out.println(weakReference.get());
        System.out.println(referenceQueue.poll());


        o1 = null;
        System.gc();
        System.out.println("************GC之后************");
        Thread.sleep(500);
        System.out.println(o1);
        System.out.println(weakReference.get());
        System.out.println(referenceQueue.poll());
    }
}
